﻿namespace NorthernLights
{
    using System;
    using System.Diagnostics;
    using System.IO;
    using System.IO.IsolatedStorage;

    /// <summary>
    /// PersistentVariables class.
    /// </summary>
    public class PersistentVariables
    {
        #region Public methods
        /// <summary>
        /// Make a persitent variable by saving it to the IsolatedStorage.
        /// </summary>
        /// <remarks>
        /// Object needs to be serializable.
        /// </remarks>
        /// <typeparam name="T">The object type.</typeparam>
        /// <param name="name">The key to use.</param>
        /// <param name="value">The object to store.</param>
        public static void Set<T>(string name, T value)
        {
            if (string.IsNullOrEmpty(name))
            {
                return;
            }

            try
            {
                using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    if (!store.DirectoryExists("Variables"))
                    {
                        store.CreateDirectory("Variables");
                    }

                    string filename = @"\Variables\" + name;

                    if (store.FileExists(filename))
                    {
                        store.DeleteFile(filename);
                    }

                    using (TextWriter output = new StreamWriter(store.OpenFile(filename, FileMode.CreateNew)))
                    {
                        output.WriteLine(Serializer.WriteFromObject<T>(value));
                    }
                }
            }
            catch
            {
            }
        }

        /// <summary>
        /// Retrieve a persitent variable from Isolated Storage.
        /// </summary>
        /// <typeparam name="T">The object type.</typeparam>
        /// <param name="name">The key to retrieve the item.</param>
        /// <returns>The stored item or default value for object type.</returns>
        public static T Get<T>(string name)
        {
            if (string.IsNullOrEmpty(name))
            {
                return default(T);
            }

            try
            {
                using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    string filename = @"\Variables\" + name;

                    if (store.DirectoryExists("Variables") && store.FileExists(filename))
                    {
                        using (TextReader reader = new StreamReader(store.OpenFile(filename, FileMode.Open, FileAccess.Read, FileShare.None)))
                        {
                            string data = reader.ReadToEnd();

                            if (!string.IsNullOrEmpty(data))
                            {
                                try
                                {
                                    return Serializer.ReadToObject<T>(data);
                                }
                                catch (Exception ex)
                                {
                                    Debug.WriteLine("Fail to restore persitent variable. Ex: " + ex.Message);
                                }
                            }
                        }
                    }
                }
            }
            catch
            {
            }

            return default(T);
        }

        /// <summary>
        /// Deletes item from persistent storage.
        /// </summary>
        /// <param name="name">The key of the item to delete.</param>
        public static void Delete(string name)
        {
            if (string.IsNullOrEmpty(name))
            {
                return;
            }

            try
            {
                using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    string filename = @"\Variables\" + name;

                    if (store.DirectoryExists("Variables") && store.FileExists(filename))
                    {
                        store.DeleteFile(filename);
                    }
                }
            }
            catch
            {
            }
        }

        /// <summary>
        /// Indicates whether the persistent variable exists or not.
        /// </summary>
        /// <param name="name">The name of the persistent variable to check.</param>
        /// <returns>True if persistent variable exists.</returns>
        public static bool Exists(string name)
        {
            if (string.IsNullOrEmpty(name))
            {
                return false;
            }

            try
            {
                using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    string filename = @"\Variables\" + name;

                    if (store.DirectoryExists("Variables") && store.FileExists(filename))
                    {
                        return true;
                    }
                }
            }
            catch
            {
            }

            return false;
        }
        #endregion
    }
}
